package com.dabai.applicationmanager.ui.smallprogram;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.dabai.applicationmanager.R;
import com.dabai.dbutils.dialog.TipAlertDialog;
import com.dabai.dbutils.toast.DBToast;
import com.dabai.dbutils.utils.SharedPreferencesBasicUse;
import com.dabai.uitools.utils.ViewUtils;
import com.google.android.material.textfield.TextInputLayout;

import java.io.File;
import java.util.Objects;

public class BatchRenameActivity extends AppCompatActivity {

    Context context;
    private TextInputLayout mTil1;
    private TextInputLayout mTil2;
    private Button mButton1;
    private TextView mTextview5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_batch_rename);
        initViews();


        context = this;

        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        TipAlertDialog.init(context);

        SharedPreferencesBasicUse.init(context);

        init();


        mTextview5.setOnLongClickListener(v -> {
            mTextview5.setText("任务列表 --");
            return true;
        });


    }

    /**
     * 初始化
     */
    private void init() {

        ViewUtils.setTextInputLayoutText(mTil1, SharedPreferencesBasicUse.getString("rename_dir", ""));
        ViewUtils.setTextInputLayoutText(mTil2, SharedPreferencesBasicUse.getString("rename_rule", "&n_&vn_&vc"));

        mButton1.setOnClickListener(v -> {
            File dir = new File(ViewUtils.getTextInputLayoutText(mTil1));

            if (!dir.exists()) {
                DBToast.showYellowToast(context, "路径目标不存在!");
                return;
            }
            if (!dir.isDirectory()) {
                DBToast.showYellowToast(context, "路径目标必须是文件夹!");
                return;
            }

            if (dir.list().length <= 0) {
                DBToast.showYellowToast(context, "文件夹必须有文件!");
                return;
            }

            SharedPreferencesBasicUse.setString("rename_dir", ViewUtils.getTextInputLayoutText(mTil1));
            SharedPreferencesBasicUse.setString("rename_rule", ViewUtils.getTextInputLayoutText(mTil2));

            for (File file1 : Objects.requireNonNull(dir.listFiles())) {

                String name;
                try {
                    name = getFileNameRule(file1);
                } catch (Exception e) {
                    ViewUtils.textViewPrintln(mTextview5,file1.getName()+" 文件异常,已跳过");
                    continue;
                }

                String socName = file1.getName();

                String suffix = socName.substring(socName.lastIndexOf("."));

                File oldFile = new File(file1.getParentFile(), socName);

                File newFile = new File(file1.getParentFile(), name+suffix);

                boolean isOk = oldFile.renameTo(newFile);
                ViewUtils.textViewPrintln(mTextview5,file1.getName()+" 命名 "+(isOk?"成功":"失败"));

            }

        });
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        com.dabai.applicationmanager.dialog.TipAlertDialog.destroyTipLayout();
    }

    private void initViews() {
        mTil1 = findViewById(R.id.til1);
        mTil2 = findViewById(R.id.til2);
        mButton1 = findViewById(R.id.button1);
        mTextview5 = findViewById(R.id.textView5);
    }


    /**
     * 获得文件名规则
     *
     * @param file 文件
     * @return {@link String}
     */
    public String getFileNameRule(File file) {

        String rule = ViewUtils.getTextInputLayoutText(mTil2);

        PackageManager packageManager = getPackageManager();

        PackageInfo packageInfo = packageManager.getPackageArchiveInfo(file.getAbsolutePath(), PackageManager.GET_ACTIVITIES);

        ApplicationInfo applicationInfo = packageInfo.applicationInfo;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            rule = rule
                    //minSdkVersion
                    .replaceAll("&msv", applicationInfo.minSdkVersion + "");
        }
        rule = rule
                //targetSdkVersion
                .replaceAll("&tsv", applicationInfo.targetSdkVersion + "")
                //uid
                .replaceAll("&uid", applicationInfo.uid + "");


        return rule
                //应用名
                .replaceAll("&n", applicationInfo.loadLabel(packageManager).toString())
                //版本名
                .replaceAll("&vn", packageInfo.versionName)
                //版本代码
                .replaceAll("&vc", "" + packageInfo.versionCode)
                //包名
                .replaceAll("&pn", packageInfo.packageName);
    }

}